package com.yyk.yiliao.ui.home.activity;

import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.donkingliang.labels.LabelsView;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;


import com.yyk.yiliao.listener.ToolbarListenter;
import com.yyk.yiliao.ui.activity.Location_Activity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.ebs.LocationEvent;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.bean.CommonScreenInfo;
import com.yyk.yiliao.bean.CommonHospitalgradeInfo;
import com.yyk.yiliao.bean.CommonTypehospitaInfo;
import com.yyk.yiliao.bean.CommoeHospital_Info;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.widget.diver.CustomDecoration;
import com.yyk.yiliao.widget.shaixuankuang.DropDownMenu;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 首页 预约挂号
 */
public class Appointment_Activity extends BaseActivity {


    private List<String> dictList = new ArrayList<>();
    private List<CommonTypehospitaInfo.DataBean> dictList2 = new ArrayList<>();
    private List<CommonHospitalgradeInfo.DataBean> dictList3 = new ArrayList<>();
    private BaseRecyclerAdapter<CommoeHospital_Info.DataBean> adapter; //预约医院列表
    //筛选  对话框 点击隐藏
    @BindView(R.id.dropDownMenu)
    DropDownMenu mDropDownMenu;
    private List<CommoeHospital_Info.DataBean> data = new ArrayList();

    private String headers[] = {"综合排序", "医院类型", "医院等级"};
    private List<View> popupViews = new ArrayList<>();


    private LabelsView constellation2;
    private LabelsView constellation3;
    //RecyckerView
    private RecyclerView contentView;

    private int gid; //医院等级
    private int hid; //医院类型

    private int currentPage = 1;

    private int type;//判断 列表类型


    @Override
    public int getLayoutId() {
        return R.layout.activity_appointment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(LocationEvent messageEvent) {
        String events = messageEvent.getEvents();
        if (events != null) {
            setMainTitleRightText(events, new ToolbarListenter() {
                @Override
                public void onClickListenter() {
                    startAct(Location_Activity.class);
                }
            });
        }
        Map<String, String> map = new TreeMap<>();
        map.put("aid", messageEvent.getAid());
        map.put("sign", Md5Util2.createSign(map));
        //不能筛选
        setAppointment(2, true, map);
    }

    private void initPost() {
        //默认全部列表
        Map<String, String> map = new TreeMap<>();
//        map.put("dis", 500000 + "");
        String weidu = Hawk.get("纬度");
        String jingdu = Hawk.get("经度");
        map.put("lon", String.valueOf(jingdu));
        map.put("lat", String.valueOf(weidu));
//        map.put("lon", String.valueOf(116.40311));
//        map.put("lat", String.valueOf(39.917548));
        Logger.d("精度" + jingdu + "唯独" + weidu);
        map.put("page", currentPage + "");
        map.put("num", "1000");


        map.put("sign", Md5Util2.createSign(map));
        setAppointment(1, true, map);
        initCommonTypehospita(true);
        initCommonHospitalgrade(true);
    }

    /**
     * 完成的时候调用
     */
    private void onComplete() {
    }

    /**
     * 预约挂号列表
     *
     * @param flag
     */
    private void setAppointment(int type, final boolean flag, Map<String, String> map) {
        switch (type) {
            //普通预约挂号列表
            case 1:
                //TODO 需要更换
                RxUtils.getInstance().retrofit.create(ApiService.class).postCommoeHospital(map)
                        .subscribeOn(Schedulers.io())     //调度线程
                        .observeOn(AndroidSchedulers.mainThread())
                        .unsubscribeOn(Schedulers.io())   //取消订阅
                        .subscribe(new Subscriber<CommoeHospital_Info>() {

                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(CommoeHospital_Info info) {
                                Logger.e("Appointement" + info.toString());
                                if (info.getCode() == 1) {
                                    contentView.setVisibility(View.VISIBLE);
                                    if (flag) {
                                        data.clear();
                                    }

                                    if (info.getData().size() > 0 && info.getData() != null) {
                                        data.addAll(info.getData());
                                    }
                                    adapter.notifyDataSetChanged();
                                } else {
                                    contentView.setVisibility(View.GONE);
                                    ToastUtil.showShort(Appointment_Activity.this, "抱歉没有更多医院了");

                                }
                            }
                        });
                break;
            //2.定位筛选挂号列表
            case 2:
                //TODO 需要更换
                RxUtils.getInstance().retrofit.create(ApiService.class).postCommonScreen(map)
                        .subscribeOn(Schedulers.io())     //调度线程
                        .observeOn(AndroidSchedulers.mainThread())
                        .unsubscribeOn(Schedulers.io())   //取消订阅
                        .subscribe(new Subscriber<CommonScreenInfo>() {

                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(CommonScreenInfo info) {
                                Logger.e("Appointement" + info.toString());
                                if (info.getCode() == 1) {
                                    contentView.setVisibility(View.VISIBLE);
                                    if (flag) {
                                        data.clear();
                                    }

                                    if (info.getData().size() > 0 && info.getData() != null) {
                                        data.addAll(info.getData());
                                    }
                                    adapter.notifyDataSetChanged();
                                } else {
                                    contentView.setVisibility(View.GONE);
                                    ToastUtil.showShort(Appointment_Activity.this, "抱歉没有更多医院了");

                                }
                            }
                        });
                break;


        }


    }

    @Override
    public void initView() {
        /**
         * 设置地址可以 用 传值
         */
        initToolbar();
        initAdapter();
    }

    private void initToolbar() {
        setBackArrow();
        setTitle("预约挂号");
        setMainTitleRightText(Hawk.get("poiName") + "", new ToolbarListenter() {
            @Override
            public void onClickListenter() {
                startAct(Location_Activity.class);
            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //3.取消注册事件
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void initData() {
        //2.注册事件
        EventBus.getDefault().register(this);
        initPost();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initAdapter() {
        //init constellation
        final View constellationView = getLayoutInflater().inflate(R.layout.custom_layout, null);
        final View constellationView2 = getLayoutInflater().inflate(R.layout.custom_layout, null);
        final View constellationView3 = getLayoutInflater().inflate(R.layout.custom_layout, null);
        LabelsView constellation = constellationView.findViewById(R.id.constellation);
        constellation2 = constellationView2.findViewById(R.id.constellation);
        constellation3 = constellationView3.findViewById(R.id.constellation);


        /**
         * 1.第一个
         */
        String[] paixu = {"离我最近", "综合排序"};
        for (int x = 0; x < paixu.length; x++) {
            dictList.add(paixu[x]);
        }
        Logger.e("医院类型等级的集合" + dictList2.size() + "----" + dictList3.size());
        //LabelsView可以设置任何类型的数据，而不仅仅是String。
        constellation.setLabels(dictList, new LabelsView.LabelTextProvider<String>() {
            @Override
            public CharSequence getLabelText(TextView label, int position, String data) {
                //根据data和position返回label需要显示的数据。
                return data;
            }
        });
        //1.标签的点击监听
        constellation.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
            @Override
            public void onLabelClick(TextView label, Object data, int position) {
                //label是被点击的标签，data是标签所对应的数据，position是标签的位置。
//                hid = dictList2.get(position).getId();
//                String name = dictList2.get(position).getName();
//                HashMap<String, String> map = new HashMap<>();
//                map.put("dis", 50000 + "");
//                String jingdu = Hawk.get("经度");
//                String weidu = Hawk.get("纬度");
//                map.put("lon", String.valueOf(weidu));
//                map.put("lat", String.valueOf(jingdu));
//                Logger.d("精度" + jingdu + "唯独" + weidu);
//                map.put("page", 1 + "");
//                map.put("num", "100");
//                map.put("hid", hid + "");
//                if (gid != 0) {
//                    map.put("gid", gid + "");
//                }
//                setAppointment(true, map);

                mDropDownMenu.setTabText(position == 0 ? headers[0] : data + "");
                mDropDownMenu.closeMenu();
            }
        });
        /**
         * 2.第二个
         *
         */

        //2.标签的点击监听
        constellation2.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
            @Override
            public void onLabelClick(TextView label, Object data, int position) {
                //label是被点击的标签，data是标签所对应的数据，position是标签的位置。

                //设置标题
                CommonTypehospitaInfo.DataBean dataBean = (CommonTypehospitaInfo.DataBean) data;
                mDropDownMenu.setTabText(position == 0 ? headers[1] : dataBean.getName() + "");
                mDropDownMenu.closeMenu();
                hid = dataBean.getId();
                Map<String, String> map = new TreeMap<>();
                map.put("dis", 50000 + "");
                String jingdu = Hawk.get("经度");
                String weidu = Hawk.get("纬度");
                map.put("lon", String.valueOf(weidu));
                map.put("lat", String.valueOf(jingdu));
                Logger.d("精度" + jingdu + "唯独" + weidu);
                map.put("page", 1 + "");
                map.put("num", "100");
                map.put("hid", hid + "");
                if (gid != 0) {
                    map.put("gid", gid + "");
                }


                map.put("sign", Md5Util2.createSign(map));
                setAppointment(1, true, map);

            }
        });
        /**
         * 3.第三个
         *
         */

        //3.标签的点击监听
        constellation3.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
            @Override
            public void onLabelClick(TextView label, Object data, int position) {
                //label是被点击的标签，data是标签所对应的数据，position是标签的位置。
                CommonHospitalgradeInfo.DataBean dataBean = (CommonHospitalgradeInfo.DataBean) data;
                mDropDownMenu.setTabText(position == 0 ? headers[2] : dataBean.getName() + "");
                mDropDownMenu.closeMenu();

                gid = dataBean.getId();

                Map<String, String> map = new TreeMap<>();
                map.put("dis", 50000 + "");
                String jingdu = Hawk.get("经度");
                String weidu = Hawk.get("纬度");
                map.put("lon", String.valueOf(weidu));
                map.put("lat", String.valueOf(jingdu));
                Logger.d("精度" + jingdu + "唯独" + weidu);
                map.put("page", 1 + "");
                map.put("num", "100");
                map.put("gid", gid + "");
                if (hid != 0) {
                    map.put("hid", hid + "");
                }
                map.put("sign", Md5Util2.createSign(map));
                setAppointment(1, true, map);

            }
        });


        /**
         * 不能同时使用一个view，可以改个名字就ok
         */
        popupViews.add(constellationView);
        popupViews.add(constellationView2);
        popupViews.add(constellationView3);
        /**
         * 底部recyclerview
         */
        contentView = new RecyclerView(this);
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        adapter = new BaseRecyclerAdapter<CommoeHospital_Info.DataBean>(Appointment_Activity.this, data, R.layout.adapter_item_hospital) {
            @Override
            public void convert(BaseRecyclerHolder holder, CommoeHospital_Info.DataBean item, int position, boolean isScrolling) {
                holder.setText(R.id.b_hospital_name, item.getHospital_name());
                int grade = item.getGrade(); //医院等级
                if (grade == 1) {
                    holder.setText(R.id.b_grade, "三级特等");
                } else if (grade == 2) {
                    holder.setText(R.id.b_grade, "三级甲等");
                } else if (grade == 3) {
                    holder.setText(R.id.b_grade, "三级乙等");
                } else if (grade == 4) {
                    holder.setText(R.id.b_grade, "三级丙等");
                } else if (grade == 5) {
                    holder.setText(R.id.b_grade, "二级甲等");
                } else if (grade == 6) {
                    holder.setText(R.id.b_grade, "二级乙等");
                } else if (grade == 7) {
                    holder.setText(R.id.b_grade, "二级丙等");
                } else if (grade == 8) {
                    holder.setText(R.id.b_grade, "一级甲等");
                } else if (grade == 9) {
                    holder.setText(R.id.b_grade, "一级乙等");
                } else if (grade == 10) {
                    holder.setText(R.id.b_grade, "一级丙等");
                } else {
                    holder.setText(R.id.b_grade, "未评级");
                }
                int hospitalType = item.getHospitalType();//医院类型
                if (hospitalType == 1) {
                    holder.setText(R.id.b_hospitalType, "血液病专科医院");
                } else if (hospitalType == 2) {
                    holder.setText(R.id.b_hospitalType, "综合医院");
                } else if (hospitalType == 3) {
                    holder.setText(R.id.b_hospitalType, "社康服务中心");
                } else if (hospitalType == 4) {
                    holder.setText(R.id.b_hospitalType, "儿童医院");
                } else if (hospitalType == 5) {
                    holder.setText(R.id.b_hospitalType, "眼科医院");
                } else if (hospitalType == 6) {
                    holder.setText(R.id.b_hospitalType, "肛肠专科医院");
                } else if (hospitalType == 7) {
                    holder.setText(R.id.b_hospitalType, "妇产科医院");
                } else if (hospitalType == 8) {
                    holder.setText(R.id.b_hospitalType, "中医医院");
                } else if (hospitalType == 9) {
                    holder.setText(R.id.b_hospitalType, "精神心理医院");
                } else if (hospitalType == 10) {
                    holder.setText(R.id.b_hospitalType, "妇幼专科医院");
                } else if (hospitalType == 11) {
                    holder.setText(R.id.b_hospitalType, "皮肤专科医院");
                } else if (hospitalType == 12) {
                    holder.setText(R.id.b_hospitalType, "健康体检中心");
                } else if (hospitalType == 13) {
                    holder.setText(R.id.b_hospitalType, "泌尿外科医院");
                } else if (hospitalType == 14) {
                    holder.setText(R.id.b_hospitalType, "口腔医院");
                } else if (hospitalType == 15) {
                    holder.setText(R.id.b_hospitalType, "骨科医院");
                } else if (hospitalType == 16) {
                    holder.setText(R.id.b_hospitalType, "胃肠专科医院");
                } else if (hospitalType == 17) {
                    holder.setText(R.id.b_hospitalType, "耳鼻喉医院");
                } else if (hospitalType == 18) {
                    holder.setText(R.id.b_hospitalType, "慢性病防治医院");
                } else if (hospitalType == 19) {
                    holder.setText(R.id.b_hospitalType, "职业病防治医院");
                } else {
                    holder.setText(R.id.b_hospitalType, "生殖专科医院详情");
                }
                holder.setText(R.id.b_address, item.getAddress());
                holder.setText(R.id.b_juli, item.getDistant() + "km");
                //设置图片
                holder.setImageByUrl(R.id.b_picture, ApiService.BASE_URL + item.getPicture());
            }
        };
        contentView.addItemDecoration(new CustomDecoration(Appointment_Activity.this, CustomDecoration.VERTICAL_LIST, R.drawable.divider_white_ef_1px, 12));
        contentView.setLayoutManager(new LinearLayoutManager(Appointment_Activity.this, LinearLayoutManager.VERTICAL, false));
        contentView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                //TODO  跳转到医院 医生列表   传值
                Intent intnet = new Intent(Appointment_Activity.this, Hospitallisting_Activity.class);
                String hospital_name = data.get(position).getHospital_name();
                intnet.putExtra("title", hospital_name);
                int hid = data.get(position).getHid();
                intnet.putExtra("hid", hid);
                startActivity(intnet);
            }
        });

        /**
         * 展示筛选框
         */
        mDropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);
    }


    /**
     * 医院等级
     */
    private void initCommonHospitalgrade(final boolean flag) {
        Map<String, String> map = new TreeMap<>();
        map.put("gid", 3 + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCommonHospitalgrade(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CommonHospitalgradeInfo>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                        onComplete();
                    }


                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();


                    }

                    @Override
                    public void onNext(CommonHospitalgradeInfo info) {
                        Logger.e("预约挂号医院等级" + info.toString());
                        if (info.getCode() == 1) {
                            if (flag) {
                                dictList3.clear();
                            }
                            if (info.getData() != null && info.getData().size() > 0) {
                                dictList3.addAll(info.getData());
                                constellation3.setLabels(dictList3, new LabelsView.LabelTextProvider<CommonHospitalgradeInfo.DataBean>() {
                                    @Override
                                    public CharSequence getLabelText(TextView label, int position, CommonHospitalgradeInfo.DataBean data) {
                                        String name = data.getName();
                                        //根据data和position返回label需要显示的数据。
                                        return dictList3.get(position).getName() + "";
                                    }
                                });
                            }


                        }
                    }


                });
    }

    /**
     * 医院类型
     */

    private void initCommonTypehospita(final boolean flag) {
        Map<String, String> map = new TreeMap<>();
        map.put("hid", 2 + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCommonTypehospita(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CommonTypehospitaInfo>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                        onComplete();
                    }


                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();


                    }

                    @Override
                    public void onNext(CommonTypehospitaInfo info) {
                        Logger.e("预约挂号医院类型" + info.toString());
                        if (info.getCode() == 1) {
                            if (flag) {
                                dictList2.clear();
                            }
                            if (info.getData() != null && info.getData().size() > 0) {
                                dictList2.addAll(info.getData());
                                constellation2.setLabels(dictList2, new LabelsView.LabelTextProvider<CommonTypehospitaInfo.DataBean>() {
                                    @Override
                                    public CharSequence getLabelText(TextView label, int position, CommonTypehospitaInfo.DataBean data) {
                                        //根据data和position返回label需要显示的数据。
                                        return data.getName() + "";
                                    }
                                });
                            }


                        }
                    }


                });
    }


}
